package de.melistik.smugmugsync.model;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.codec.binary.Base64;

public class UsersPreferences {

	Logger LOGGER = Logger.getLogger(UsersPreferences.class.getName());
	private static final String propertiesFilename = "jsmugsync.properties";

	String username;
	String password;
	String syncStartPath;

	public UsersPreferences() {

	}

	public UsersPreferences(String username, String password,
			String syncStartPath) {
		setUsername(username);
		setPassword(password);
		setSyncStartPath(syncStartPath);
	}

	public boolean storeSettings() {
		boolean result = false;
		Properties prop = new Properties();
		try {

			if (getUsername() != null)
				prop.setProperty("username", getUsername());
			if (getPassword() != null)
				prop.setProperty("password",
						Base64.encodeBase64String(getPassword().getBytes()));
			if (getSyncStartPath() != null)
				prop.setProperty("syncStartPath", getSyncStartPath());

			prop.store(new FileOutputStream(propertiesFilename), null);
			result = true;
		} catch (IOException ex) {
			LOGGER.log(Level.SEVERE, "error storing properties", ex);
		}
		return result;
	}

	public boolean readSettings() {
		boolean result = false;
		Properties prop = new Properties();
		try {
			prop.load(new FileInputStream(propertiesFilename));

			setUsername(prop.getProperty("username"));
			String propPassword = prop.getProperty("password");
			if (propPassword != null)
				setPassword(new String(Base64.decodeBase64(propPassword
						.getBytes())));
			setSyncStartPath(prop.getProperty("syncStartPath"));
			result = true;
		} catch (FileNotFoundException ex) {
			LOGGER.log(Level.INFO, "no existing properties-file");
		} catch (IOException ex) {
			LOGGER.log(Level.SEVERE, "error reading properties", ex);
		}
		return result;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSyncStartPath() {
		return syncStartPath;
	}

	public void setSyncStartPath(String syncStartPath) {
		this.syncStartPath = syncStartPath;
	}

}
